
#include <iostream>

#include "Events.h"
#include "Message.h"
#include "Serializer.h"

Message::Message()
{
	//cstr_ = new std::string("");
    time_stamp = x = y = wheel_delta = key = event_type = modifier = 0;
}

Message::~Message()
{
	//delete cstr_;
}

Message& Message::Parse(const abyte* data, int* parsed_length, Message& result)
{
    data += Serializer::DeserializeInt<uint32_t>(data, &result.time_stamp);
    result.event_type = *data++;
    result.coordinate_type = *data++;
	data += Serializer::DeserializeInt<int16_t>(data, &result.x);
	data += Serializer::DeserializeInt<int16_t>(data, &result.y);
    
    printf("Parsed message: x/y=%hd/%hd\n", result.x, result.y);
    
    result.key = result.x;

    return result;
}

void Message::GetBytes(abyte* buffer)
{
    buffer += Serializer::SerializeInt(time_stamp, buffer);
    *buffer++ = event_type;
    *buffer++ = coordinate_type;
    AddDeviceData(buffer);
}

void Message::AddDeviceData(abyte* buffer)
{
    switch (event_type)
    {
        case kEventKeyDown:
        case kEventKeyUp:
            
            //length = sz_keyboard;
            //*buffer++ = key;
            break;
            
        case kEventMouseEnter:
        case kEventMouseLeave:
        case kEventRightMouseDown:
        case kEventRightMouseUp:
        case kEventMouseDown:
        case kEventMouseMove:
        case kEventMouseUp:
        case kEventLeftMouseDoubleClick:
            
            //length = sz_mouse;
            GetXY(x, y, buffer);
            break;
            
        case kEventMouseWheel:
            
            //length = sz_mouse;
            GetXY(0, wheel_delta, buffer);
            break;
            
        case kEventNone:
            break;
            
        default:
            printf("An unsupported event type \"%d\" was specified\n", event_type);
            //return NULL;
    }
    
    //return length;
}

void Message::GetXY(short x, short y, abyte* buffer)
{
    buffer += Serializer::SerializeInt(x, buffer);
    buffer += Serializer::SerializeInt(y, buffer);
}

/*const char* Message::ToString()
{
    return cstr_->c_str();
}*/